package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.client.BehaviorFeign;
import com.heima.common.constants.article.ArticleConstans;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.user.client.UserFeign;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-19
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApAuthorService apAuthorService;

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Override
    @Transactional
    public Long saveArticle(WmNewsResultDTO dto) {
        //保存文章
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(dto.getTitle());
        //根据自媒体用户id查询作者
        ApAuthor apAuthor = apAuthorService.findByWmUserId(dto.getWmUserId());
        apArticle.setAuthorId(apAuthor.getId());
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setChannelId(dto.getChannelId());
        apArticle.setChannelName(dto.getChannelName());
        apArticle.setLayout(dto.getType());
        apArticle.setFlag(0);
        apArticle.setImages(dto.getImages());
        apArticle.setLabels(dto.getLabels());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(dto.getPublishTime());
        apArticle.setIsComment(true);
        apArticle.setIsForward(true);
        apArticle.setIsDelete(false);
        apArticle.setIsDown(false);
        apArticle.setWmNewsId(dto.getId());
        //保存文章内容
        boolean b = this.save(apArticle);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存文章数据失败");
        }
        Long articleId = apArticle.getId();
        //保存文章内容
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(articleId);
        apArticleContent.setContent(dto.getContent());
        boolean b1 = apArticleContentService.save(apArticleContent);
        if(!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存文章内容失败");
        }
        return articleId;
    }

    @Override
    public void updateIsDown(Map<String, Integer> map) {
        UpdateWrapper<ApArticle> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ApArticle::getWmNewsId,map.get("wmNewsId")).
                set(ApArticle::getIsDown,map.get("enable")==1?0:1);
        boolean b = this.update(updateWrapper);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新文章上下架失败");
        }
    }

    @Override
    public List<ArticleDto> load(ArticleHomeDto dto, int type) {
        //组装查询条件
        Integer size = dto.getSize();
        if(size==null || size==0){
            size=10;
        }
        //组装分页条件
        Page<ApArticle> page = new Page<>(1,size);
        //组装查询条件
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper();
        String tag = dto.getTag();
        if(StringUtils.isNotBlank(tag) && !"__all__".equals(tag)){
            //组装基于频道id查询文章列表条件
            queryWrapper.lambda().eq(ApArticle::getChannelId,tag);
        }
        //文章是非下架，非删除状态
        queryWrapper.lambda().eq(ApArticle::getIsDelete,false).eq(ApArticle::getIsDown,false);

        if(type==1){
            //加载更多文章 load more 文章的发布时间 小于页面提交的最小时间
            queryWrapper.lambda().lt(ApArticle::getPublishTime,dto.getMinBehotTime());
        }else{
            //加载最新文章 load new  文章的发布时间 大于页面提交的最大时间
            queryWrapper.lambda().gt(ApArticle::getPublishTime,dto.getMaxBehotTime());
        }

        //可以基于发布时间倒序排序
        queryWrapper.lambda().orderByDesc(ApArticle::getPublishTime);
        //执行查询
        IPage<ApArticle> iPage = this.page(page, queryWrapper);
        if(CollectionUtils.isEmpty(iPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章列表数据不存在");
        }
        List<ArticleDto> articleDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), ArticleDto.class);
        return articleDtoList;
    }

    @Autowired
    private IApCollectionService collectionService;

    @Override
    public Map<String, Object> loadArticleInfo(ArticleInfoDto dto) {
        Map<String,Object> map = new HashMap<>();
        if(dto.getArticleId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章表数据
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticle::getId,dto.getArticleId()).
                eq(ApArticle::getIsDown,false).eq(ApArticle::getIsDelete,false);
        //执行查询
        ApArticle apArticle = this.getOne(queryWrapper);
        if(apArticle==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在");
        }
        map.put("config",apArticle);
        //查询文章内容表数据
        QueryWrapper<ApArticleContent> contentQueryWrapper = new QueryWrapper<>();
        contentQueryWrapper.lambda().eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent articleContent = apArticleContentService.getOne(contentQueryWrapper);
        map.put("content",articleContent);
        return map;
    }

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public Map<String, Boolean> loadArticleBehavior(ArticleInfoDto dto) {
        //1、设置属性，判断是用户行为还是设备行为
        Boolean isUser=false;
        //2、获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId!=null && userId!=0) {
            isUser=true;
        }
        //3、参数校验
        if(userId==null && dto.getEquipmentId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //4、查询用户行为  包含收藏、 点赞、不喜欢（行为微服务完成）、关注（用户微服务完成）
        //4.1 查询收藏行为
        QueryWrapper<ApCollection> collectionQueryWrapper = new QueryWrapper<>();
        collectionQueryWrapper.lambda().eq(ApCollection::getArticleId,dto.getArticleId())
                .eq(ApCollection::getType,0);
        if(isUser){
            collectionQueryWrapper.lambda().eq(ApCollection::getApUserId,userId);
        }else {
            collectionQueryWrapper.lambda().eq(ApCollection::getEquipmentId,dto.getEquipmentId());
        }
        //执行查询
        int count = collectionService.count(collectionQueryWrapper);

        //4.1 查询点赞、不喜欢（行为微服务完成）
        Map<String, Boolean> map = behaviorFeign.findBehavior(userId, dto.getEquipmentId(), dto.getArticleId(), 0);
        //4.2 查询 关注（用户微服务完成）
        Boolean isfollow=false;
        if(isUser){
            //查询作者的App用户id值
            ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
            Integer followId = apAuthor.getUserId();
            Boolean boo = userFeign.findByUserIdAndFollowId(userId, followId);
            if(boo){
                isfollow=true;
            }
        }
        map.put("iscollection",count>0);
        map.put("isfollow",isfollow);
        return map;
    }

    @Override
    public List<ArticleDto> findByPage(int page, int size) {
        //构建分页条件
        Page<ApArticle> articlePage = new Page<>(page,size);
        //查询未下架、未删除文章列表
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticle::getIsDelete,false).eq(ApArticle::getIsDown,false);
        //执行查询
        IPage<ApArticle> iPage = this.page(articlePage, queryWrapper);
        if(CollectionUtils.isEmpty(iPage.getRecords())){
            return null;
        }
        List<ArticleDto> articleDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), ArticleDto.class);
        return articleDtoList;
    }

    @Autowired
    private IApHotArticlesService hotArticlesService;

    @Override
    public List<ArticleDto> loadFirst(ArticleHomeDto dto) {
        Integer channelId=0;
        if(!dto.getTag().equals(ArticleConstans.DEFAULT_TAG)){
            channelId = Integer.parseInt(dto.getTag());
        }

        return hotArticlesService.getHotArticle(channelId);
    }
}
